package com.yunxi.service.dubboService.impl.sto;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.yunxi.baseDataToHub.pojo.sap.PartnerInfoVO;
import com.yunxi.baseDataToHub.service.sap.SapDubboService;
import com.yunxi.core.util.BeanTools;
import com.yunxi.core.util.WgrDate;
import com.yunxi.core.web.ApiResult;
import com.yunxi.model.sto.StoStorageCompany;
import com.yunxi.model.sto.StoStorageStaff;
import com.yunxi.service.localService.CodeCreateService;
import com.yunxi.service.localService.sto.StoStorageCompanyService;
import com.yunxi.service.localService.sto.StoStorageStaffService;
import com.yunxi.sto.pojo.StoStorageCompanyListVO;
import com.yunxi.sto.pojo.StoStorageCompanyVO;
import com.yunxi.sto.service.StoStorageCompanyDubboService;
import com.yunxi.sto.service.StoStorageStaffDubboService;
import com.yunxi.util.S2SEnums;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 仓储公司 服务实现类
 * </p>
 *
 * @author caoYong
 * @since 2019-06-06
 */
public class StoStorageCompanyDubboServiceImpl implements StoStorageCompanyDubboService {

    @Autowired
    @Qualifier(value = "stoStorageCompanyServiceImpl")
    StoStorageCompanyService stoStorageCompanyService;

    @Autowired
    @Qualifier(value = "codeCreateServiceImpl")
    CodeCreateService codeCreateService;

    @Autowired
    SapDubboService sapDubboServiceImpl;

    @Autowired
    @Qualifier(value = "stoStorageStaffServiceImpl")
    StoStorageStaffService stoStorageStaffService;

    @Autowired
    @Qualifier(value = "stoStorageStaffDubboServiceImpl")
    StoStorageStaffDubboService stoStorageStaffDubboService;

    @Override
    public StoStorageCompanyVO getById(String id) {
        StoStorageCompany stoStorageCompany = stoStorageCompanyService.getById(id);
        StoStorageCompanyVO stoStorageCompanyVO = new StoStorageCompanyVO();
        BeanTools.copyProperties(stoStorageCompanyVO,stoStorageCompany);
        return stoStorageCompanyVO;
    }

    /**
     * 维护
     * @param stoStorageCompanyVO
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    @Override
    public void saveOrUpdate(StoStorageCompanyVO stoStorageCompanyVO) throws Exception {
        StoStorageCompany stoStorageCompany = new StoStorageCompany();
        BeanTools.copyProperties(stoStorageCompany,stoStorageCompanyVO);
        //校验名称不可重复
        checkCompanyName(stoStorageCompanyVO);
        //校验编号不可重复
        checkCompanyNo(stoStorageCompanyVO);
        String storageCompanyNo = stoStorageCompany.getStorageCompanyNo();

        if(stoStorageCompanyVO.getStorageCompanyId() == null){
            String sgc = codeCreateService.createCode("SGC", 4);
            stoStorageCompany.setStorageCompanyNo(sgc);
            stoStorageCompany.setIsOnUse("1");//新建默认启用

            pms2SAP(stoStorageCompanyVO, S2SEnums.OperatorType.insert.getKey());
        }else{
            pms2SAP(stoStorageCompanyVO, S2SEnums.OperatorType.update.getKey());
        }
        stoStorageCompanyService.saveOrUpdate(stoStorageCompany);
    }

    private boolean pms2SAP(StoStorageCompanyVO partnerVO, String op) throws Exception {
        PartnerInfoVO partnerInfoVO = setPropPartnerInfoVO(partnerVO);

        setOrgInfo(partnerVO, partnerInfoVO, null, "2");

        partnerInfoVO.setIndicator(op);
        ApiResult apiResult1 = sapDubboServiceImpl.savePartnerInfoToSap(partnerInfoVO);
        if (apiResult1.getCode().equals(-1)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return true;
        }
        return false;
    }

    private void setOrgInfo(StoStorageCompanyVO partnerVO, PartnerInfoVO partnerInfoVO, String superCode, String type) throws Exception {
        partnerInfoVO.setZobl1(superCode);//上级渠道CODE
        partnerInfoVO.setZobl3(WgrDate.getCurrentTime(3));//修改时间
        //partnerInfoVO.setZobl4();//备注
        partnerInfoVO.setType(type);//类型状态 1渠道商，2物流公司

      /*ApiResult apiResult1 = sapDubboServiceImpl.savePartnerInfoToSap(partnerInfoVO);
      if (apiResult1.getCode().equals(-1)) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         logger.error("  ------- sapDubboServiceImpl.savePartnerInfoToSap 执行失败 ___组织机构信息  ---------  ");
         return true;
      }
      return false;*/
    }

    //设置sap渠道属性
    private PartnerInfoVO setPropPartnerInfoVO(StoStorageCompanyVO partnerVO) {
        PartnerInfoVO partnerInfoVO = new PartnerInfoVO();
        partnerInfoVO.setKunnr(partnerVO.getStorageCompanyNo());
        partnerInfoVO.setName1(partnerVO.getStorageCompanyName());
        partnerInfoVO.setSortl(partnerVO.getStorageCompanyName());
        partnerInfoVO.setStras(partnerVO.getStorageCompanyAddress());
        partnerInfoVO.setTelf1(partnerVO.getContactPersonPhone());
        partnerInfoVO.setMobil(partnerVO.getContactPersonPhone());
        partnerInfoVO.setContact(partnerVO.getContactPersonName());
        partnerInfoVO.setVkorg(partnerVO.getStorageCompanyNo());

        return partnerInfoVO;
    }

    /**
     * 校验仓储公司编号不可重复
     * @param stoStorageCompanyVO
     * @throws Exception
     */
    private void checkCompanyNo(StoStorageCompanyVO stoStorageCompanyVO) throws Exception {
        QueryWrapper<StoStorageCompany> queryWrapper = new QueryWrapper();
        queryWrapper.eq("STORAGE_COMPANY_NO",stoStorageCompanyVO.getStorageCompanyNo());
        if(stoStorageCompanyVO.getStorageCompanyId() != null){
            queryWrapper.ne("STORAGE_COMPANY_ID",stoStorageCompanyVO.getStorageCompanyId());
        }
        List<StoStorageCompany> list = stoStorageCompanyService.list(queryWrapper);
        if(list != null && list.size() > 0){
            throw new Exception("操作失败,仓储公司编号:"+stoStorageCompanyVO.getStorageCompanyNo()+"已存在!");
        }
    }

    /**
     * 校验公司名称不可重复
     * @param stoStorageCompanyVO
     * @throws Exception
     */
    private void checkCompanyName(StoStorageCompanyVO stoStorageCompanyVO) throws Exception {
        QueryWrapper<StoStorageCompany> queryWrapper = new QueryWrapper();
        queryWrapper.eq("STORAGE_COMPANY_NAME",stoStorageCompanyVO.getStorageCompanyName());
        if(stoStorageCompanyVO.getStorageCompanyId() != null){
            queryWrapper.ne("STORAGE_COMPANY_ID",stoStorageCompanyVO.getStorageCompanyId());
        }
        List<StoStorageCompany> list = stoStorageCompanyService.list(queryWrapper);
        if(list != null && list.size() > 0){
            throw new Exception("操作失败,仓储公司名称:"+stoStorageCompanyVO.getStorageCompanyName()+"已存在!");
        }
    }

    @Override
    public void removeById(String id) {
    stoStorageCompanyService.removeById(id);
    }

    @Override
    public PageInfo<StoStorageCompanyVO> findPageByVO(StoStorageCompanyVO stoStorageCompanyVO, Integer pageNum, Integer pageSize) {
        PageInfo<StoStorageCompanyVO> pageInfo = stoStorageCompanyService.pageByVo(stoStorageCompanyVO, pageNum, pageSize);
        return pageInfo;
    }

    /**
     * 导出
     * @param stoStorageCompanyVO
     * @return
     * @throws Exception
     */
    @Override
    public List<StoStorageCompanyVO> export(StoStorageCompanyVO stoStorageCompanyVO) throws Exception {
        List<StoStorageCompanyVO> list = stoStorageCompanyService.export(stoStorageCompanyVO);
        return list;
    }

    @Override
    public void removeByListVo(List<StoStorageCompanyVO> stoStorageCompanyVOList) throws Exception {
        stoStorageCompanyService.removeByListVo(stoStorageCompanyVOList);

        for(int i=0;i<stoStorageCompanyVOList.size();i++){
            StoStorageCompanyVO stoStorageCompanyVO = stoStorageCompanyVOList.get(i);
            pms2SAP(stoStorageCompanyVO, S2SEnums.OperatorType.delete.getKey());
        }

    }

    /**
     * 启用/停用
     * @param list
     * @param isOnUse
     * @throws Exception
     */
    @Override
    public void delAndReset(List<String> list, String isOnUse,String userId) throws Exception {
        if(list != null && list.size() > 0){
            for (String id : list){
                StoStorageCompany stoStorageCompany = stoStorageCompanyService.getById(id);
                if(stoStorageCompany != null){
                    stoStorageCompany.setIsOnUse(isOnUse);
                    stoStorageCompany.setUpdateBy(userId);
                    stoStorageCompanyService.updateById(stoStorageCompany);
                    //仓储公司停用/启用,所属人员全部部停用/启用
                    changeStorageStaffState(id,isOnUse,userId);
                }
                else {
                    throw new Exception("操作失败.无法根据主键id:"+id+"找到对应仓储公司!");
                }
            }
        }
        else{
            throw new Exception("操作失败.list为空!");
        }
    }

    /**
     * 停用/启用仓储人员使用状态
     * @param id
     * @throws Exception
     */
    private void changeStorageStaffState(String id,String isOnUse,String userId) throws Exception {
        QueryWrapper<StoStorageStaff> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("STORAGE_COMPANY_ID",id);
        List<StoStorageStaff> list1 = stoStorageStaffService.list(queryWrapper);
        //启用仓储公司,不同时启用下属人员
        if(list1 != null && list1.size() > 0 && isOnUse.equals("0")){
            List<String> staffIdList = new ArrayList<>();
            for (StoStorageStaff stoStorageStaff : list1){
                staffIdList.add(stoStorageStaff.getStorageStaffId());
            }
            stoStorageStaffDubboService.delAndReset(staffIdList,isOnUse,userId);
        }
    }

    /**
     * 仓储公司列表
     * @return
     * @throws Exception
     */
    @Override
    public List<StoStorageCompanyListVO> companyList(String isOnUse) throws Exception {
        return stoStorageCompanyService.companyList(isOnUse);
    }
}
